<?php

class UploaderController extends MyController
{	
	var $current_folder = "upload";
	
	function init() {parent::init(); }
	
	function actionIndex()
	{	
		$this->redirect(array($this->controller_id.'/view'));
	}
	
	function actionView($current_folder = "upload")
	{
		$current_folder = urldecode($current_folder);
		
		$dirs = dir($this->create_path($current_folder));
		
		$files = array();
		$folders = array();
		
		while($entry = $dirs->read())
		{
			if ($entry == '.' or $entry =='..')	continue;
			
			$entry_path = $this->create_path($current_folder) .'/'.$entry;
			
			if ( ! is_dir($entry_path))
			{
				$file = array();
				$filetype = strtolower(substr($entry, strrpos($entry,'.')+1));
				
				$filesize = filesize($entry_path);
				$file["name"] = $entry;
				$file["type"] = '.'.$filetype;
				$file["size"] = $filesize;
				
				$files[] =  $file;
			}else{ // folder
				if (strcmp($entry, "mcith") !=0 )
					$folders[] = $entry;
			}
				
		}
		
		$this->data["files"] = $files;
		$this->data["folders"] = $folders;
		$this->data["current_folder"] = $current_folder;
		$this->render("view", $this->data);
	}
	
	function actionCreate_folder($current_folder)
	{
		$current_folder = urldecode($current_folder);
		$folder_name = trim(mii::clear_sign(Yii::app()->getRequest()->getPost("folder_name")));
		
		if (!file_exists(WEB_ROOT . "/" . $current_folder . "/" . $folder_name))
			@ mkdir(WEB_ROOT . "/" . $current_folder."/".$folder_name);
		$this->redirect(array(
			$this->controller_id."/view", 
			"current_folder" => urlencode($current_folder)
		));
	}
	
	function actionDelete_folder($current_folder, $folder_name)
	{
		$current_folder = urldecode($current_folder);
		
		if (file_exists(WEB_ROOT ."/" . $current_folder . "/" . $folder_name))
			@ rmdir(WEB_ROOT . "/" . $current_folder."/".$folder_name);
		$this->redirect(array(
			$this->controller_id."/view", 
			"current_folder" => urlencode($current_folder)
		));
	}
	
	function actionDelete_file($current_folder, $file_name)
	{
		$current_folder = urldecode($current_folder);
		
		if (file_exists(WEB_ROOT . "/" . $current_folder ."/" . $file_name))
			@ unlink(WEB_ROOT . "/" . $current_folder."/".$file_name);
		$this->redirect(
			array($this->controller_id."/view", 
			"current_folder" => urlencode($current_folder))
		);
	}
	
	
	function actionUpload($current_folder)
	{
		$current_folder = urldecode($current_folder);
		
		$file = CUploadedFile::getInstanceByName("file");
		if ($file)
		{
			$file_name = trim(mii::clear_sign($file->name));
			$file->saveAs($this->create_path($current_folder)."/".$file_name);
		}
		
		$this->redirect(
			array($this->controller_id."/view", 
			"current_folder" => urlencode($current_folder))
		);
			
	}
	
	//ok
	function create_path($path_folder)
	{
		return WEB_ROOT."/".$path_folder;
	}
}